package com.spring.pay.weixin.handler;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;
import org.json.JSONException;

import com.spring.pay.weixin.client.TenpayHttpClient;
import com.spring.pay.weixin.util.XMLUtil;

public class PrepayIdRequestHandler extends RequestHandler {

	public PrepayIdRequestHandler(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}



	// 提交预支付
	@SuppressWarnings("rawtypes")
	public String sendPrepay() throws JSONException, JDOMException, IOException {
		String prepayid = "";
		//要传到微信的数据map
		Map map = super.getAllParameters();
		
		//将sortedMap转换成xml
		String params = XMLUtil.mapToXml(map);

		String requestUrl = super.getGateUrl();
		this.setDebugInfo(this.getDebugInfo() + "\r\n" + "requestUrl:" + requestUrl);
		TenpayHttpClient httpClient = new TenpayHttpClient();
		httpClient.setReqContent(requestUrl);
		String resContent = "";
		this.setDebugInfo(this.getDebugInfo() + "\r\n" + "post data:" + params);
		if (httpClient.callHttpPost(requestUrl, params)) {
			
			resContent = httpClient.getResContent();
			
			Map resMap = XMLUtil.doXMLParse(resContent);
			if(map != null){
				//微信返回的return_code="SUCCESS",生成预支付交易会话标识成功
				if(resMap.get("return_code").equals("SUCCESS")){
					//得到预支付交易会话标识,并返回
					prepayid = (String)resMap.get("prepay_id");
				}
			}
			this.setDebugInfo(this.getDebugInfo() + "\r\n" + "resContent:" + resContent);
		}
		return prepayid;
	}


}
